package org.yi.web.account;

import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yi.core.annotation.Action;
import org.yi.core.common.Constants;
import org.yi.web.account.entity.AccountEntity;
import org.yi.web.base.BaseController;

import com.jfinal.ext.render.CaptchaRender;

@Action(action = "/admin/account")
public class AccountController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(AccountController.class);

	public void login() {
		// if request method is GET, render login.html
		if(isGetMethod()) {
			render("login.html");
		} else {
			String vcode = getPara(Constants.VERIFY_CODE);
			//if verify code is blank or not equals verify code in session, return login.html
			if(CaptchaRender.validate(this, vcode.toUpperCase(), Constants.VERIFY_CODE)) {
				addError("verify code error!");
				this.keepPara();
				this.render("/login.html");
			} else {
				Subject currentUser = SecurityUtils.getSubject();
				//if agent has not login, return the index page
				if(currentUser.isAuthenticated()) {
					redirect("/agent/list");
				} else {
					UsernamePasswordToken token = new UsernamePasswordToken(getPara("loginname"), getPara("passwd"));
					if(getParaToBoolean("remeberme")) {
						token.setRememberMe(true);
					}
		            try {
		                currentUser.login(token);
		                redirect("/agent/list");
		            } catch (UnknownAccountException e) {
		            	addError("username ["+token.getPrincipal()+"] not found!");
		            	logger.error(e.getMessage(), e);
		            	render("/login.html");
		            } catch (IncorrectCredentialsException e) {
		            	addError("password error!");
		            	logger.error(e.getMessage(), e);
		                render("/login.html");
		            } catch (LockedAccountException e) {
		            	addError("user ["+token.getPrincipal()+"] locked!");
		            	logger.error(e.getMessage(), e);
		                render("/login.html");
		            } catch (Exception e) {
		                addError("unknow error: " + e.getMessage());
		                logger.error(e.getMessage(), e);
		                render("/login.html");
		            }
		        }
			}
		}
	}
	
	
	public void regist(){
		AccountEntity account = getModel(AccountEntity.class);
		if(AccountEntity.dao.getByName(account.getStr("login_name")) == null) {
			if(account.save()) {
				redirect("/login");
			} else {
				addError("create [" + account.getStr("login_name") + "] error!");
				keepPara();
				render("regist.html");
			}
		} else {
			addError("user [" + account.getStr("login_name") + "] exist!");
			keepPara();
			render("regist.html");
		}
	}
	
	
	
	/**
	 * ajax判断用户是否可注册
	 */
	public void exists() {
		Map<String,Object> obj = new HashMap<String,Object>();
		obj.put("exist", AccountEntity.dao.userExist(getPara("key")));
		renderJson(obj);
	}
	
	/**
	 *  用户退出登录
	 */
	public void logout(){
		SecurityUtils.getSubject().logout();
		getSession().invalidate();
		redirect("/");
	}
}
